﻿using System;
using System.Collections.Generic;
using System.Text;
using NORM.Common;
using NORM.Entity;

namespace NORM.SQLObject
{
    public class OQLOrder : OQLComponent
    {
        protected OQL currentOql;

        internal OQLOrder(OQL oql)
        {
            this.Key = "OQLOrder";
            this.Guid = "dce98dea-7dfc-448a-8e17-b28582154bd4";
            this.currentOql = oql;
        }

        public bool Asc(object Field)
        {
            if (currentOql != null)
            {
                string fieldstring = Field + "";
                if (currentOql.fieldStack.Count > 0)
                {
                    TableField tf = currentOql.fieldStack.Pop();
                    fieldstring = tf.Entity.TableName + "." + tf.Field;
                }

                if (!currentOql._join && fieldstring.Contains("."))
                {
                    fieldstring = fieldstring.Substring(fieldstring.LastIndexOf(".") + 1);
                }

                List<object> ordebies= ArrayPlus.ToList<object>(currentOql.Orderbies);
                ordebies.Add(fieldstring + " ASC");

                currentOql.OrderBy(ordebies.ToArray());

                return true;

            }

            return false;
        }

        public bool Desc(object Field)
        {
            if (currentOql != null)
            {
                string fieldstring = Field + "";
                if (currentOql.fieldStack.Count > 0)
                {
                    TableField tf = currentOql.fieldStack.Pop();
                    fieldstring = tf.Entity.TableName + "." + tf.Field;
                }

                if (!currentOql._join && fieldstring.Contains("."))
                {
                    fieldstring = fieldstring.Substring(fieldstring.LastIndexOf(".") + 1);
                }

                List<object> ordebies = ArrayPlus.ToList<object>(currentOql.Orderbies);
                ordebies.Add(fieldstring + " DESC");

                currentOql.OrderBy(ordebies.ToArray());

                return true;

            }

            return false;
        }

    }
}
